package com.ruoyi.material.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.basicsystem.domain.ZnDepot;
import com.ruoyi.basicsystem.domain.ZnSupplier;
import com.ruoyi.basicsystem.service.IZnDepotService;
import com.ruoyi.basicsystem.service.IZnSupplierService;
import com.ruoyi.bill.domain.DepotItemVo4WithInfoEx;
import com.ruoyi.bill.domain.ERPReportExport;
import com.ruoyi.bill.domain.ExportParam;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.ChineseCharToEn;
import com.ruoyi.material.domain.*;
import com.ruoyi.material.service.IZnMaterialAttributeService;
import com.ruoyi.material.service.IZnMaterialCategoryService;
import com.ruoyi.material.service.IZnMaterialInitialStockService;
import com.ruoyi.system.domain.ZnMaterialProperty;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.material.service.IZnMaterialService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 产品Controller
 * 
 * @author ruoyi
 * @date 2021-12-24
 */
@RestController
@RequestMapping("/material/material")
public class ZnMaterialController extends BaseController
{
    @Autowired
    private IZnMaterialService znMaterialService;
    @Autowired
    private IZnMaterialAttributeService znMaterialAttributeService;
    @Autowired
    private IZnDepotService znDepotService;
    @Autowired
    private IZnMaterialInitialStockService znMaterialInitialStockService;
    @Autowired
    private IZnMaterialCategoryService znMaterialCategoryService;

    @Autowired
    private IZnSupplierService znSupplierService ;
    /**
     * 导出商品库存查询
     * @author nexiaozi
     * @date 2022-06-23
     */
    @Log(title = "（导出报表数据）导出库存查询", businessType = BusinessType.EXPORT)
    @PostMapping("/stockExport")
    public void stockExport(HttpServletResponse response, ExportParam exportParam)
    {
        Long categoryId = exportParam.getCategoryId();
        String depotIds = exportParam.getDepotIds();
        String column = exportParam.getColumn();
        String order = exportParam.getOrder();
        String materialParam= exportParam.getMaterialParam();
        Integer zeroStock = exportParam.getZeroStock();
        List<Long> idList = new ArrayList<>();
        List<Long> depotList = new ArrayList<>();
        if(categoryId != null){
            idList = znMaterialCategoryService.getListByParentId(categoryId);
        }
        if(StringUtil.isNotEmpty(depotIds)) {
            depotList = StringUtil.strToLongList(depotIds);
        } else {
            //未选择仓库时默认为当前用户有权限的仓库
            JSONArray depotArr = znDepotService.findDepotByCurrentUser();
            for(Object obj: depotArr) {
                JSONObject object = JSONObject.parseObject(obj.toString());
                depotList.add(object.getLong("id"));
            }
        }
//        startPage();
        if(column==null){
            column="createTime";
        }
        if(order==null){
            order="desc";
        }
//        startPage();
        List<MaterialVo4Unit> dataList = znMaterialService.getListWithStock(depotList, idList, StringUtil.toNull(materialParam), zeroStock,
                StringUtil.safeSqlParse(column), StringUtil.safeSqlParse(order));
        List<MaterialStockExportVo> result = new ArrayList<>();
        for (MaterialVo4Unit vo:dataList) {
            MaterialStockExportVo  materialStockExportVo= new MaterialStockExportVo();
            BeanUtils.copyProperties(vo,materialStockExportVo);
            result.add(materialStockExportVo);
        }
        ExcelUtil<MaterialStockExportVo> util = new ExcelUtil<MaterialStockExportVo>(MaterialStockExportVo.class);
        util.exportExcel(response, result, "库存查询");
    }
    /**
     * 商品库存查询

     * @param depotIds
     * @param categoryId
     * @param materialParam
     * @param zeroStock
     * @param column
     * @param order
     * @param request
     * @return
     * @throws Exception
     */
    @PreAuthorize("@ss.hasAnyPermi('report:materialstock:list')")
    @GetMapping(value = "/getListWithStock")
    public AjaxResult getListWithStock(
                                             @RequestParam(value = "depotIds", required = false) String depotIds,
                                             @RequestParam(value = "categoryId", required = false) Long categoryId,
                                             @RequestParam(value = "materialParam", required = false) String materialParam,
                                             @RequestParam(value = "zeroStock", required = false) Integer zeroStock,

                                             @RequestParam(value = "column", required = false) String column,
                                             @RequestParam(value = "order", required = false) String order,
                                             HttpServletRequest request)throws Exception {
        AjaxResult res = new AjaxResult();
        Map<String, Object> map = new HashMap<>();
            List<Long> idList = new ArrayList<>();
            List<Long> depotList = new ArrayList<>();
            if(categoryId != null){
                idList = znMaterialCategoryService.getListByParentId(categoryId);
            }
            if(StringUtil.isNotEmpty(depotIds)) {
                depotList = StringUtil.strToLongList(depotIds);
            } else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = znDepotService.findDepotByCurrentUser();
                for(Object obj: depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getLong("id"));
                }
            }
            startPage();
            if(column==null){
                column="createTime";
            }
            if(order==null){
                order="desc";
            }
            List<MaterialVo4Unit> dataList = znMaterialService.getListWithStock(depotList, idList, StringUtil.toNull(materialParam), zeroStock,
                    StringUtil.safeSqlParse(column), StringUtil.safeSqlParse(order));
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(dataList);
            rspData.setTotal(new PageInfo(dataList).getTotal());

           // int total = materialService.getListWithStockCount(depotList, idList, StringUtil.toNull(materialParam), zeroStock);
            MaterialVo4Unit materialVo4Unit= znMaterialService.getTotalStockAndPrice(depotList, idList, StringUtil.toNull(materialParam));

            res.put("data",rspData);
            res.put("currentStock", materialVo4Unit.getCurrentStock());
            DecimalFormat df = new DecimalFormat("0.00");
            res.put("currentStockPrice", materialVo4Unit.getCurrentStockPrice()!=null?df.format(materialVo4Unit.getCurrentStockPrice()):0);
/*
            map.put("total", total);
            map.put("currentStock", materialVo4Unit.getCurrentStock());
            map.put("currentStockPrice", materialVo4Unit.getCurrentStockPrice());*/
            //存放数据json数组
           /* map.put("rows", dataList);
            res.code = 200;
            res.data = map;*/

        return res;
    }
    /**
     * 查询产品列表
     */
    @PreAuthorize("@ss.hasPermi('material:material:list')")
    @GetMapping("/list")
    public TableDataInfo list(ZnMaterial znMaterial)
    {
        startPage();
        if(StringUtils.isNotBlank(znMaterial.getName())){
            znMaterial.setChineseChar(znMaterial.getName().trim().toUpperCase());
            znMaterial.setName(znMaterial.getName().trim());
        }
        Map<String,Object> params = new HashMap<>();
        params.put("defaultFlag",1);
        znMaterial.setParams(params);
        List<ZnMaterial> list = znMaterialService.selectZnMaterialList(znMaterial);
        return getDataTable(list);
    }
    /**
     * 查询所有商品期初库存列表
     */
    //@PreAuthorize("@ss.hasPermi('material:depot:list')")
    @GetMapping("/listMeteralInitialStock")
    public AjaxResult listMeteralInitialStock(ZnMaterial znMaterial)
    {
        ZnDepot znDepot =new ZnDepot();
        znDepot.setDeleteFlag("0");
        znDepot.setTenantId(SecurityUtils.getLoginUser().getUser().getTenantId());
        List<ZnDepot> listDeport = znDepotService.selectZnDepotList(znDepot);

        Collections.sort(listDeport, new Comparator<ZnDepot>() {
            @Override
            public int compare(ZnDepot o1, ZnDepot o2) {
                if(StringUtils.isEmpty(o1.getSort())){
                    return -1;
                }
                if(StringUtils.isEmpty(o2.getSort())){
                    return -1;
                }
                return o1.getSort().compareTo(o2.getSort());
            }
        });
        List<ZnMaterialInitialStock> znMaterialInitialStocks=new ArrayList<>();

        if(znMaterial.getId()==null){
            ZnMaterialInitialStock znMaterialInitialStock=null;
            for(ZnDepot depor:listDeport){
                znMaterialInitialStock=new ZnMaterialInitialStock();
                znMaterialInitialStock.setNumber(NumberUtil.toBigDecimal(0));
                znMaterialInitialStock.setDepotId(depor.getId());
                znMaterialInitialStock.setDepotName(depor.getName());
                znMaterialInitialStocks.add(znMaterialInitialStock);
            }

        }else{
            ZnMaterialInitialStock znMaterialInitialStock=null;
            ZnMaterialInitialStock znMaterialInitialStockQuery=new ZnMaterialInitialStock();
            znMaterialInitialStockQuery.setMaterialId(znMaterial.getId());
            List<ZnMaterialInitialStock>    zntocks = znMaterialInitialStockService.selectZnMaterialInitialStockList(znMaterialInitialStockQuery);

            for(ZnDepot depor:listDeport){
                boolean f=false;
                for(ZnMaterialInitialStock stockTemp:zntocks){
                    if(stockTemp.getDepotId().longValue()==depor.getId().longValue()){
                        f=true;
                        stockTemp.setDepotName(depor.getName());//设置名称
                        znMaterialInitialStocks.add(stockTemp);
                        break;
                    }
                }
                if(!f){//不存在 就用仓库的
                    znMaterialInitialStock=new ZnMaterialInitialStock();
                    znMaterialInitialStock.setNumber(NumberUtil.toBigDecimal(0));
                    znMaterialInitialStock.setDepotId(depor.getId());
                    znMaterialInitialStock.setDepotName(depor.getName());
                    znMaterialInitialStocks.add(znMaterialInitialStock);
                }

            }
        }


        return AjaxResult.success(znMaterialInitialStocks);
    }


    /**
     * 导出产品列表
     */
    @PreAuthorize("@ss.hasPermi('material:material:export')")
    @Log(title = "产品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ZnMaterial znMaterial)
    {
        List<ZnMaterial> list = znMaterialService.selectZnMaterialList(znMaterial);
        ExcelUtil<ZnMaterial> util = new ExcelUtil<ZnMaterial>(ZnMaterial.class);
        util.exportExcel(response, list, "产品数据");
    }
    /**
     * 导出产品模板
     */
    @PreAuthorize("@ss.hasPermi('material:material:export')")
    @Log(title = "导出产品模板", businessType = BusinessType.EXPORT)
    @PostMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response, ZnMaterial znMaterial)
    {
        ExcelUtil<ZnMaterial> util = new ExcelUtil<ZnMaterial>(ZnMaterial.class);
        util.exportExcel(response, new ArrayList<>(), "产品数据");
    }

    /**
     * 获取产品详细信息
     */
    @PreAuthorize("@ss.hasPermi('material:material:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(znMaterialService.selectZnMaterialById(id));
    }
    /**
     * 检查名称是否重复
     */
    @PutMapping(value = "/checkMaterNameIsEx")
    public AjaxResult checkMaterNameIsEx(@RequestBody ZnMaterial znMaterial)
    {
        if(znMaterial.getId()==null||znMaterial.getId()==0){//新增传0
            znMaterial.setId(null);
        }
        int i=znMaterialService.checkMaterNameIsEx(znMaterial);
        Map<String,Object> map=new HashMap<>();
        if(i==0){
            map.put("chineseChar",StringUtil.getPinYinHeadChar(znMaterial.getName().trim()));
        }
        map.put("isName",i);
        return AjaxResult.success(map);
    }
    /**
     * 新增产品
     */
    @PreAuthorize("@ss.hasPermi('material:material:add')")
    @Log(title = "产品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ZnMaterial znMaterial)
    {
        if(StringUtils.isNotBlank(znMaterial.getName())){
            znMaterial.setName(znMaterial.getName().trim());
        }
        return znMaterialService.insertZnMaterial(znMaterial);
    }
    /**
     * 新增产品页面数据
     */
    @PreAuthorize("@ss.hasPermi('material:material:add')")
    @Log(title = "产品", businessType = BusinessType.INSERT)
    @GetMapping(value = "/goAdd")
    public AjaxResult goAdd()
    {
        Map remap=new HashMap();
        //获取多属性
        ZnMaterialAttribute znMaterialAttribute=new ZnMaterialAttribute();
        List<ZnMaterialAttribute> attributeList = znMaterialAttributeService.selectZnMaterialAttributeList(znMaterialAttribute);
        List<String> attributeValue=null;
        Map fieldmap=new HashMap();
        for(ZnMaterialAttribute nMaterialAttribute:attributeList){
            attributeValue=new ArrayList<>();
            if(StringUtils.isNotEmpty(nMaterialAttribute.getAttributeValue())){
            String[] strs=    nMaterialAttribute.getAttributeValue().split("\\|");
             for(String str:strs){
                 attributeValue.add(str);
             }
            }
            nMaterialAttribute.setVauleList(attributeValue);
            fieldmap.put(nMaterialAttribute.getAttributeField(),nMaterialAttribute);
        }
        remap.put("attribute",fieldmap);
        return AjaxResult.success(remap);
    }
    /**
     * 修改产品
     */
    @PreAuthorize("@ss.hasPermi('material:material:edit')")
    @Log(title = "产品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ZnMaterial znMaterial)
    {
        znMaterial.setName(znMaterial.getName().trim());
        return znMaterialService.updateZnMaterial(znMaterial);
    }

    /**
     * 删除产品
     */
    @PreAuthorize("@ss.hasPermi('material:material:remove')")
    @Log(title = "产品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(znMaterialService.deleteZnMaterialByIds(ids));
    }

    /**
     * 启用禁用产品
     */
    @PreAuthorize("@ss.hasPermi('material:material:remove')")
    @Log(title = "产品", businessType = BusinessType.DELETE)
    @PutMapping("/handleEnableMaterial/{ids}/{enable}")
    public AjaxResult handleEnableMaterial(@PathVariable Long[] ids,@PathVariable Integer enable)
    {
        return toAjax(znMaterialService.handleEnableMaterial(ids,enable));
    }

    /**
     * 获取最大条码
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getMaxBarCode")
   // @ApiOperation(value = "获取最大条码")
    public AjaxResult getMaxBarCode() throws Exception {
        AjaxResult res = new AjaxResult();
        Map<String, Object> map = new HashMap<String, Object>();
        String barCode = znMaterialService.getMaxBarCode();
        map.put("barCode", barCode);

        return AjaxResult.success(map);
    }

    /**
     * 查询产品列表
     */
    @PreAuthorize("@ss.hasPermi('bill:retail:add')")
    @GetMapping("/selectlist")
    public TableDataInfo selectlist(ZnMaterial znMaterial)
    {
        logger.debug(JSON.toJSONString(znMaterial));
        if(!znMaterial.getParams().isEmpty()){
            if(znMaterial.getParams().containsKey("customerId")){
                Long customerId = Long.parseLong(znMaterial.getParams().get("customerId").toString());
                ZnSupplier customer = znSupplierService.selectZnSupplierById(customerId);
                Map<String,Object> params = znMaterial.getParams();
                params.put("isAgree",customer.getIsAgree());
                params.put("customerId",customerId);
                znMaterial.setParams(params);
            }
        }
        startPage();
        if(znMaterial.getParams().containsKey("name")){
            String name = znMaterial.getParams().get("name").toString();
            Map<String,Object> params = znMaterial.getParams();
            params.put("name",name.trim());
            znMaterial.setParams(params);
        }
        if(znMaterial.getParams().containsKey("materialExtentIds")){
            String materialExtentIdsStr = znMaterial.getParams().get("materialExtentIds").toString();
            if(StringUtils.isNotBlank(materialExtentIdsStr)){
                Map<String,Object> params = znMaterial.getParams();
                params.put("materialExtendIds",materialExtentIdsStr.split(","));
                znMaterial.setParams(params);
            }
        }
        List<ZnMaterial> list = znMaterialService.selectZnMaterialSelectList(znMaterial);
        return getDataTable(list);
    }
    /**
     * 查询产品列表
     */
    @PreAuthorize("@ss.hasPermi('basicsystem:agreement:add')")
    @GetMapping("/listAll")
    public AjaxResult listAll(ZnMaterial znMaterial)
    {
        List<ZnMaterial> list = znMaterialService.selectZnMaterialAllList(znMaterial);
        return AjaxResult.success(list);
    }

    /**
     * 商品信息导入
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "商品信息导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('material:material:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        Date startDate = new Date();
        String startStr = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",startDate);
        logger.debug("开始导入数据！");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String operName = loginUser.getUsername();
        ExcelUtil<ZnMaterial> util = new ExcelUtil<ZnMaterial>(ZnMaterial.class);
        List<ZnMaterial> list = util.importExcel(file.getInputStream());
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            return AjaxResult.error("导入数据不能为空！");
        }
        logger.debug("导入数据："+list.size());
        String message = znMaterialService.importMaterialList(list, updateSupport, operName);
//        String message = znMaterialService.importMaterial(file, updateSupport, operName);
        logger.debug("结束导入数据！");
        Date endDate = new Date();
        String endStr =  DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",endDate);
        logger.debug("开始时间："+startStr +",结束时间：" + endStr);
        logger.debug("用时："+(endDate.getTime()-startDate.getTime()));
        logger.debug("用时："+(endDate.getTime()-startDate.getTime())/1000+"s");
        return AjaxResult.success(message);
    }
}
